package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.pojo.SkuInfo;
import com.changgou.search.dao.SearchMapper;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SearchMapper searchMapper;

    @Autowired
    private SkuFeign skuFeign;

    @Override
    public void deleteIndexAndMaping() {
        //elasticsearchTemplate.deleteIndex("skuinfo");
        elasticsearchTemplate.deleteIndex(SkuInfo.class);
    }

    @Override
    public void createIndexAndMapping() {
        //创建索引库
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射关系
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importBySpuId(String spuId) {
        //1.根据spuId查询sku的商品列表
        List<Sku> skuList = skuFeign.findBySpuId(spuId);

        //2.处理数据保存到ES
        importDataToES(skuList);
    }






    @Override
    public void importAll() {

        //1.查询所有sku数据
        //2.处理数据保存到ES
        List<Sku> skuList = skuFeign.findAll();

        importDataToES(skuList);

    }

    private void importDataToES(List<Sku> skuList) {
        if (skuList != null && skuList.size() > 0) {
            //1.1将sku列表数据转为JSON
            String skuListJson = JSON.toJSONString(skuList);

            //1.2将JSON转为skuinfo对应的列表
            List<SkuInfo> skuInfoList = JSON.parseArray(skuListJson, SkuInfo.class);

            //1.3处理specmap属性
            for (SkuInfo skuInfo : skuInfoList) {
                String specJSON = skuInfo.getSpec(); //获取商品对应的specJSON字符串
                //将JSON字符串转换为map类型
                Map specMap = JSON.parseObject(specJSON, Map.class);
                skuInfo.setSpecMap(specMap);

            }

            //2.导入全部数据到ES中
            searchMapper.saveAll(skuInfoList);
        }
    }

    @Override
    public void deleteBySpuId(String spuId) {
        //1.根据spuId查询到商品数据
        List<Sku> skuList = skuFeign.findBySpuId(spuId);

        if(skuList!=null && skuList.size()>0){
            for (Sku sku : skuList) {
                //2.删除商品数据
                searchMapper.deleteById(Long.valueOf(sku.getId())); //根据sku的商品ID删除即可。原因是sku的id跟skuinfo的id值是一样的。
            }
        }

    }
}
